<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */

namespace app\api\controller;


use app\api\model\ccPush;
use app\api\model\small\XcxRelationDouble;
use app\api\model\TelephoneNotification;
use redis\RedisPackage;
use shortLink\WxService;
use think\Controller;
use app\index\model\Jpush;
use app\api\model\Aliyunoss;
use Think\Db;
use think\Exception;
use think\Cache;
use think\Request;
use  app\api\model\OrderModel;
use unionpay\AppUtil;
use think\Log;
use app\api\model\Approval;
use app\api\model\Common;

class Callback extends Controller
{
    
    public function notify()
    {
        $receipt = file_get_contents("php://input");
        $attr    = $this->xmlToArray($receipt);
        cache::set('微信回调', $receipt);
        journal(['url' => '微信回调', 'data' => $attr], 1);
        $sign = $attr['sign'];
        unset($attr['sign']);
        $key = 'yiniao20190125102349567745433212';//微信商户平台支付设置的key
        ksort($attr);//根据key升序排序
        $str = http_build_query($attr) . "&key=" . $key;
        urldecode($str);
        $signValue = strtoupper($sign);
        
        //验签名。默认支持MD5
        if ($sign === $signValue) {
            if ($attr['result_code'] == 'SUCCESS' && $attr['return_code'] == "SUCCESS") {
                $order_id = db('direct_payment_record', config('database.zong'))
                    ->join('direct_order', 'direct_payment_record.serial_number=direct_order.payNo', 'left')
                    ->join('order_info', 'order_info.order_id=direct_payment_record.order_id', 'left')
                    ->join('order', 'order.order_id=direct_payment_record.order_id', 'left')
                    ->where('direct_payment_record.serial_number', $attr['out_trade_no'])
                    ->field('CONCAT(order_info.province,order_info.city,order_info.county,order.addres) as address,direct_payment_record.name,direct_payment_record.order_id,direct_payment_record.price,direct_payment_record.quantity,direct_payment_record.state,direct_payment_record.purchase_id')
                    ->find();
                if ($order_id['state'] == 0) {
                    db('direct_payment_record', config('database.zong'))->where('serial_number', $attr['out_trade_no'])->update(['state' => 1, 'payment_time' => time(), 'out_trade_no' => $attr['transaction_id']]);
                    $def1 = sprintf('%.2f', $order_id['price'] * $order_id['quantity'] * 0.0054);
                    if (!empty($order_id['purchase_id'])) {
                        U8cMasters('收到' . $order_id['address'] . $order_id['name'] . '打压完成', sprintf('%.2f', ($order_id['price'] * $order_id['quantity'])), $order_id['order_id'], 23, 2, 1, $def1, $order_id['purchase_id']);
                    }
                }
                
            }
        }
        
        
    }
    
    public function alinotify()
    {
        $val = Request::instance()->post();
        $get = Request::instance()->get();
        
        $return = isset($val) ? $val : $get;
        journal(['url' => '支付宝回调', 'data' => $return], 1);
        cache::set('支付宝回调', $return);
        
        $ok = $this->verify_sign($return, 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnKhSw4FLhZrXGc8yw7UWgpqafFlvIEWfzSuQrPAeuhb8z/WOoAfGxaoStWnAKpd7RInxcXSVk11L9DlaCTGwgAa5ViaeLEmxBWnfbWBgtPubvo+ugxvVucBFHQVB0Do3KxX6I4kX0Tg+BCSHldEPclY7VbNJm6/RiWjXzuFwuNhvy/FB+BaYAGcFWfrzuIdWg6fBe7RiOyBRbqLD15Evx9AZBoixoXarcr+h4wQzFOzbH1mLx+npfX9Qr5fkVzQQ0BkeDkKfrNY/ez4bQkU7LWjdlzm/PMycLFIec2rQ/KPCQU+KGYJXaAtRJo16GtGagrEo+kKdAkb3Zpw7SsAZfQIDAQAB');
        if ($ok) {
            $order_id = db('direct_payment_record', config('database.zong'))
                ->join('direct_order', 'direct_payment_record.serial_number=direct_order.payNo', 'left')
                ->join('order_info', 'order_info.order_id=direct_payment_record.order_id', 'left')
                ->join('order', 'order.order_id=direct_payment_record.order_id', 'left')
                ->where('direct_payment_record.serial_number', $return['out_trade_no'])
                ->field('CONCAT(order_info.province,order_info.city,order_info.county,order.addres) as address,direct_payment_record.name,direct_payment_record.order_id,direct_payment_record.price,direct_payment_record.quantity,direct_payment_record.state,direct_payment_record.purchase_id')
                ->find();
            if ($order_id['state'] == 0) {
                db('direct_payment_record', config('database.zong'))->where('serial_number', $return['out_trade_no'])->update(['state' => 1, 'payment_time' => time(), 'out_trade_no' => $return['trade_no']]);
                if (!empty($order_id['purchase_id'])) {
                    U8cMasters('收到' . $order_id['address'] . $order_id['name'] . '打压完成', sprintf('%.2f', ($order_id['price'] * $order_id['quantity'])), $order_id['order_id'], 23, 12, 0, 0, $order_id['purchase_id']);
                }
            }
            
        }
        echo "success";        //请不要修改或删除
        
    }
    
    /*
     * 支付宝回调验证
     */
    public function verify_sign($params, $alipay_public_key, $sign_type = 'RSA2')
    {
        $ori_sign = $params['sign'];
        unset($params['sign']);
        unset($params['sign_type']);
        ksort($params);
        $data = '';
        foreach ($params as $k => $v) {
            $data .= $k . '=' . $v . '&';
        }
        $data           = substr($data, 0, -1);
        $public_content = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($alipay_public_key, 64, "\n", true) . "\n-----END PUBLIC KEY-----";
        $public_key     = openssl_get_publickey($public_content);
        if ($public_key) {
            if ($sign_type == 'RSA2') {
                $result = (bool)openssl_verify($data, base64_decode($ori_sign), $public_key, OPENSSL_ALGO_SHA256);
            } else {
                $result = (bool)openssl_verify($data, base64_decode($ori_sign), $public_key);
            }
            openssl_free_key($public_key);
            return $result;
        } else {
            return false;
        }
    }
    
    
    /**
     * @return bool
     * 回调
     */
    
    public function hui(OrderModel $orderModel, \app\api\model\Common $common)
    {
        
        $receipt = file_get_contents("php://input");
        $citys   = '';
        $attr    = $this->xmlToArray($receipt);
        foreach ($attr as $k => $v) {
            if ($k == 'sign') {
                $xmlSign = $attr[$k];
                unset($attr[$k]);
            };
            if ($k == 'city') {
                $citys   = $attr[$k];
                $xmlSign = $attr[$k];
                unset($attr[$k]);
            };
        }
        
        $sign = http_build_query($attr);
        //md5处理
        $sign = md5($sign . '&key=yiniao20190125102349567745433212');
        //转大写
        $sign = strtoupper($sign);
        if (!empty($citys)) {
            if ($citys != "cd") {
                $city = \config('database.' . $citys);
            } else {
                $city = '';
            }
            
        } else {
            Log::write(json_encode(['APP' => '微信支付城市参数错误', 'log' => $attr], JSON_UNESCAPED_UNICODE), 'error', true);
        }
        
        db()->startTrans();
        //验签名。默认支持MD5
        if ($sign === $xmlSign) {
            if ($attr['return_code'] == 'SUCCESS' && $attr['result_code'] == "SUCCESS") {
                $order_status = db('recharge', $city)->join('order', 'order.order_no=recharge.order_no', 'left')
                    ->field('recharge.*,order.order_id,order.state')
                    ->where('recharge.order_nos', $attr['out_trade_no'])
                    ->find();
                
                if ($attr['attach'] == 1) {
                
                } elseif ($attr['attach'] == 2) {
                    /*
                    * 首先判断，订单是否已经更新为ok，因为微信会总共发送8次回调确认
                    * 其次，订单已经为ok的，直接返回SUCCESS
                    * 最后，订单没有为ok的，更新状态为ok，返回SUCCESS
                    */
                    
                    if ($order_status['status'] == 1) {
                        $this->return_success();
                    } else {
                        $updata['status']          = 1;
                        $updata['last_login_time'] = time();
                        $upt['success']            = 2;
                        $upt['uptime']             = time();
                        db('payment', $city)->where(['payment_id' => $order_status['project']])->update($upt);
                        $res = db('recharge', $city)->where('order_nos', $attr['out_trade_no'])->update($updata);
                        \db('order_times')->where('order_id', $order_status['order_id'])->where('first_payment_time', 0)->update(['first_payment_time' => $updata['last_login_time']]);
                        if (isset($order_status['youhui_id']) && $order_status['youhui_id'] != '') {
                            if ($order_status['coupon_version'] == 1) {
                                db('coupon_user', config('database.zong'))->where(['id' => $order_status['youhui_id']])->update(['usage_status' => 2, 'usage_time' => time()]);
                            } else {
                                db('discount', $city)->where(['youhui_id' => $order_status['youhui_id'], 'customers_id' => $order_status['customers_id']])->update(['status' => 1]);
                            }
                        }
                        if ($res) {
                            // $cust = db('customers', config('database.zong'))->where('customers_id', $order_status['customers_id'])->find();
                            if ($order_status['state'] == 3) {
                                $offer             = $orderModel->TotalProfit($order_status['order_id']);
                                $all_amount_main   = strval($offer['MainMaterialMoney']);
                                $all_amount_agency = strval($offer['agencyMoney']);
                                $paymentMoney = db('payment')->where('payment.orders_id', $order_status['order_id'])->whereRaw('money>0 and IF(weixin=2,success=2,success=1) and orders_id>0')->sum('money');
                              
                                if ($paymentMoney / bcadd($all_amount_main, $all_amount_agency, 2) >= 0.499) {
                                   
                                    $node_code         = Db::connect(config('database.zong'))->table('order_payment_nodes')->where('order_id', $order_status['order_id'])->where('payment_id', $order_status['project'])->value('node_code');
                                    if (bcadd($all_amount_main, $all_amount_agency, 2) >= 10000 || ($all_amount_main < 10000 && $node_code != 0) || $all_amount_main == '0.00' || $paymentMoney >= bcadd($all_amount_main, $all_amount_agency, 2)) {
                                        $common->CommissionCalculation($order_status['order_id'], $orderModel);
                                        db('order')->where(['order_id' => $order_status['order_id']])->update(['state' => 4]);
                                        remind($order_status['order_id'], 4);
                                    }
                                }
                            }
                            
                            Log::write(json_encode(['APP' => '微信支付城市', 'log' => $attr]), 'log', true);
                            db()->commit();
                            json_decode(sendOrder($order_status['order_id']), true);
                            automaticEntry($order_status['order_id'], $order_status['project']);
                            send_post('http://api.shopowner.yiniao.co/api/Callback/twitterCall?orderId=' . $order_status['order_id'] . '&city=' . $citys, [], 1);
                            $this->return_success();
                        }
                    }
                    
                } elseif ($attr['attach'] == 3) {
                    Db::name('common_logs')->insert(['content' => json_encode('回调成功！'), 'created_at' => time()]);
                    /*
                    * 首先判断，订单是否已经更新为ok，因为微信会总共发送8次回调确认
                    * 其次，订单已经为ok的，直接返回SUCCESS
                    * 最后，订单没有为ok的，更新状态为ok，返回SUCCESS
                    */
                    if ($order_status['status'] == 1) {
                        $this->return_success();
                    } else {
                        $updata['status']          = 1;
                        $updata['last_login_time'] = time();
                        $res                       = db('recharge')->where('order_nos', $attr['out_trade_no'])->update($updata);
                        if ($res !== false) {
                            $xcx_relation_double = db('xcx_relation_double')->where(['order_sn' => $attr['out_trade_no']])->find();
                            if ($xcx_relation_double['pid_type'] == 2) {
                                $personal = db('personal')->where(['personal_id' => $xcx_relation_double['pid']])->find();
                                $xcx      = rand(40, 60);
                                db('personal')->where(['personal_id' => $xcx_relation_double['pid']])->update(['sheng' => ($xcx + $personal['sheng'])]);
                            } else {
                                $condition = ['customer_id' => $order_status['customers_id'], 'order_sn' => $attr['out_trade_no']];
                                Db::name('common_logs')->insert(['content' => json_encode($condition), 'created_at' => time()]);
                                $update_data = ['status' => XcxRelationDouble::STATUS_ALREADY, 'pay_at' => time()];
                                if (db('xcx_relation_double')->where($condition)->update($update_data) === false) {
                                    throw new Exception('修改活动状态失败');
                                }
                                $discount_res = db('discount')->where(['customers_id' => $order_status['customers_id'], 'youhui_id' => 1])->find();
                                if ($discount_res != null && $discount_res['status'] != 0) {
                                    $this->return_success();
                                }
                                if ($discount_res == null) {
                                    $discount_data = [
                                        'customers_id' => $order_status['customers_id'],
                                        'youhui_id' => 1,
                                        'created_time' => time(),
                                        'status' => 0,
                                        'double' => 1,
                                    ];
                                    if (!db('discount')->insert($discount_data)) {
                                        throw new Exception('关联优惠券失败');
                                    }
                                }
                                if ($xcx_relation_double['pid'] != 0) {
                                    if (db('discount')->where(['customers_id' => $xcx_relation_double['pid'], 'status' => 0, 'youhui_id' => 1])->setInc('double') === false) {
                                        throw new Exception('升级关联优惠券失败');
                                    }
                                }
                            }
                            db()->commit();
                            $this->return_success();
                        }
                    }
                }
            } else {
                echo '微信支付失败';
                Log::write(json_encode(['APP' => '微信支付', 'log' => $attr], JSON_UNESCAPED_UNICODE), 'error', true);
            }
            
        }
        
    }
    
    public function twitterCall(OrderModel $orderModel, \app\api\model\Common $common)
    {
        $data = Request::instance()->get();
//        $customers = db('order')
//            ->field('order.assignor,order.order_id,order.state,order.order_no,us.mobile,order.created_time,order.channel_details,order.notcost_time,order.channel_id,chanel.thousand,chanel.title,channel_details.Included as Includeds,channel_details.thousand as thousands,channel_details.title as titles,order.tui_jian,order.tui_role,order.pro_id')
//            ->join('user us', 'us.user_id=order.assignor', 'left')
//            ->join('chanel', 'order.channel_id=chanel.id', 'left')
//            ->join('channel_details', 'order.channel_details=channel_details.id', 'left')
//            ->where('order.order_id', $data['orderId'])
//            ->find();
        $common->CommissionCalculation($data['orderId'], $orderModel);
        
        
    }
    
    /*
     * 将xml格式转换成数组
     */
    private function xmlToArray($xml)
    {
        
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        
        $val = json_decode(json_encode($xmlstring), true);
        
        return $val;
    }
    
    private function return_success()
    {
        $return['return_code'] = 'SUCCESS';
        $return['return_msg']  = 'OK';
        $xml_post              = '<xml>
                    <return_code>' . $return['return_code'] . '</return_code>
                    <return_msg>' . $return['return_msg'] . '</return_msg>
                    </xml>';
        echo $xml_post;
        exit;
    }
    
    public function enterprise()
    {
        
        include_once EXTEND_PATH . 'work/WXBizMsgCrypt.php';
        $encodingAesKey   = "0SzrAAmUgNRKttDnB7FoB6HQ1ABPVLudTXae8enj8Xe";
        $token            = "i9fabmU4TuCwjyrLquSpmnOop";
        $corpId           = "wwafc9a61f8dd402b1";
        $sVerifyMsgSig    = $_GET["msg_signature"];
        $sVerifyTimeStamp = $_GET["timestamp"];
        $sVerifyNonce     = $_GET["nonce"];
//        $sVerifyEchoStr   = $_GET["echostr"];// 需要返回的明文
//        $sEchoStr         = "";
        $wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
//        $errCode          = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
//        if ($errCode == 0) {
//            echo $sEchoStr;00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
//        } else {
//            print("ERR: " . $errCode . "\n\n");
//        }
        $sMsg    = ""; //解析之后的明文
        $receipt = file_get_contents("php://input");
        $errCode = $wxcpt->DecryptMsg($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $receipt, $sMsg);
        
        if ($errCode == 0) {
            Cache::set(34, $sMsg);
            $attr = $this->xmlToArray($sMsg);
            foreach ($attr['ApprovalInfo']['SpRecord'] as $value) {
                if (is_array($value) && count($value) == 2) {
                    $timeKey = array_column($value, 'SpStatus'); //取出数组中status的一列，返回一维数组
                    array_multisort($timeKey, SORT_DESC, $value);
                    foreach ($value as $item) {
                        $statues = 0;
                        if ($item['SpStatus'] == 3) {
                            $bo = 3;
                        }
                        if ($item['SpStatus'] == 2) {
                            $statues = 2;
                        }
                    }
                } else {
                    $bo      = $attr['ApprovalInfo']['SpRecord']['SpStatus'];
                    $statues = $attr['ApprovalInfo']['SpRecord']['SpStatus'];
                }
                
            }
            if ($attr['ApprovalInfo']['TemplateId'] == '3TmACnEeaNnzBa2rNYCCRH75ZacUaDdfKw3VxnWy') {
                if ($bo == 3) {
                    $purchase_usage = db('purchase_usage')->where('sp_no', $attr['ApprovalInfo']['SpNo'])->find();
                    if ($purchase_usage) {
                        db('purchase_usage')->where('sp_no', $attr['ApprovalInfo']['SpNo'])->update(['status' => 2, 'adopt' => time()]);
                    } else {
                        db('routine_usage')->where('sp_no', $attr['ApprovalInfo']['SpNo'])->update(['status' => 2, 'adopt' => time()]);
                    }
                    
                } elseif ($statues == 2) {
                    $purchase_usage = db('purchase_usage')->where('sp_no', $attr['ApprovalInfo']['SpNo'])->find();
                    if ($purchase_usage) {
                        db('purchase_usage')->where('sp_no', $attr['ApprovalInfo']['SpNo'])->update(['status' => 1, 'adopt' => time()]);
                    } else {
                        db('routine_usage')->where('sp_no', $attr['ApprovalInfo']['SpNo'])->update(['status' => 1, 'adopt' => time()]);
                    }
                }
                
            } elseif ($attr['ApprovalInfo']['TemplateId'] == 'Bs7uczfFFNujAN7v9f9EX3MfDoM2WoFjdDRPtZ1hx') {
                if ($bo == 3) {
                    db('reimbursement')->where('sp_no', $attr['ApprovalInfo']['SpNo'])->update(['status' => 2, 'adopt' => time()]);
                } elseif ($statues == 2) {
                    db('reimbursement')->where('sp_no', $attr['ApprovalInfo']['SpNo'])->update(['status' => 1, 'adopt' => time()]);
                }
                
            }
            
            
        }
    }
    
    /*
     * 电话回调
     */
    
    public function phone(Request $request)
    {
        
        $receipt = $request->all();
        if (strpos($receipt['main'], 'customer') !== false) {
            $shopowner = 1;
        } else {
            $shopowner = 0;
            
        }
        $receipt = object_array($receipt);
        $data    = [
            'ring' => strtotime($receipt['Ring']),
            'end' => strtotime($receipt['End']),
            'calltimelength' => $receipt['CallTimeLength'],
            'exten' => $receipt['Exten'],
            'state' => $receipt['State'],
            'encryptiontoken' => $receipt['main'],
            'monitorfilename' => $receipt['MonitorFilename'],
            'shopowner' => $shopowner,
        ];
        
        Db::connect(config('database.cc'))->table('conversation')->insertGetId($data);
        
    }
    
    /*
     * 通联支付开发者中心回调
     */
    
    public function cash(OrderModel $orderModel, \app\api\model\Common $common)
    {
        $receipt = file_get_contents("php://input");
        
        if ($receipt == null) {
            $receipt = $GLOBALS['HTTP_RAW_POST_DATA'];
        }
        
        parse_str($receipt, $query_arr);
        $receipt        = $query_arr;
        $order_status   = db('recharge')
            ->join('order', 'order.order_no=recharge.order_no', 'left')
            ->join('user', 'order.assignor=user.user_id', 'left')
            ->where('recharge.order_nos', $receipt['outtrxid'])
            ->find();
        $orderId        = $order_status['order_id'];
        $registrationId = $order_status['registrationId'];
        $addres         = $order_status['addres'];
        $userID         = $order_status['assignor'];

//        $receipt['key'] = 55265108912;
        $encryption = $common->encryption($order_status['company_id']);
//            if(empty($encryption[1])){
//                throw new Exception('加密签名获取失败');
//            }
        $receipt['key'] = $encryption[1];
        $attr           = $receipt;
        journal(['url' => '通联支付', 'data' => $attr], 1);
        unset($receipt['sign']);
        $sign = AppUtil::Sign($receipt);
        
        if ($sign == strtolower($attr['sign'])) {
            
            $order_status = db('recharge')->where('order_nos', $attr['outtrxid'])->order('recharge_id desc')->find();
            
            $order_payment_nodes       = db('order_payment_nodes', config('database.zong'))->where('order_id', $orderId)->where('payment_id', $order_status['project'])->find();
            $updata['status']          = 1;
            $updata['last_login_time'] = time();
            $updata['chnltrxid']       = $attr['chnltrxid'];
            $upt['success']            = 2;
            $upt['uptime']             = time();
            $res                       = false;
            $new                       = new Jpush();
            \db('order_times')->where('order_id', $orderId)->where('first_payment_time', 0)->update(['first_payment_time' => $updata['last_login_time']]);
            if (empty($order_status['chnltrxid']) && $order_status['status'] == 0) {
                db('payment')->where(['payment_id' => $order_status['project']])->update($upt);
                db('recharge')->where('recharge_id', $order_status['recharge_id'])->update($updata);
                $res = true;
                automaticEntry($orderId, $order_status['project']);
                // $data = ['order_id' => $orderId, 'content' => $addres . $order_payment_nodes['node_title'] . $order_payment_nodes['node_money'] . '已入账，查看详情', 'type' => 2, 'user_id' => $userID];
                // $new->tui('', $registrationId, $data);
             
            }
            if (!empty($order_status['chnltrxid']) && $order_status['chnltrxid'] == $attr['chnltrxid'] && $order_status['status'] == 0) {
                db('payment')->where(['payment_id' => $order_status['project']])->update($upt);
                db('recharge')->where('recharge_id', $order_status['recharge_id'])->update($updata);
                $res = true;
                automaticEntry($orderId, $order_status['project']);
                // $data = ['order_id' => $orderId, 'content' => $addres . $order_payment_nodes['node_title'] . $order_payment_nodes['node_money'] . '已入账，查看详情', 'type' => 2, 'user_id' => $userID];
                // $new->tui('', $registrationId, $data);
               
            }
            if (!empty($order_status['chnltrxid']) && $order_status['chnltrxid'] != $attr['chnltrxid'] && $attr['trxstatus'] == 0000) {
                
                $moneySum      = $attr['trxamt'] / 100;
                $customersList = db('order')->where('order.order_no', $order_status['order_no'])->find();
                $project       = db('payment')->insertGetId(['uptime' => time(), 'orders_id' => $customersList['order_id'], 'weixin' => 2, 'success' => 1, 'material' => $moneySum, 'money' => $moneySum, 'created_time' => time(), 'pay_type' => 1]);
                db('recharge')->insertGetId(['project' => $project, 'order_nos' => $attr['outtrxid'], 'order_no' => $order_status['order_no'], 'money' => $moneySum, 'status' => 1, 'last_login_time' => time(), 'created_time' => time(), 'type' => 2, 'mode' => 4, 'pay_type' => 1, 'chnltrxid' => $attr['chnltrxid'], 'payment_method' => 1]);
                $res = true;
                automaticEntry($orderId, $order_status['project']);
                // $data = ['order_id' => $orderId, 'content' => $addres . $order_payment_nodes['node_title'] . $order_payment_nodes['node_money'] . '已入账，查看详情', 'type' => 2, 'user_id' => $userID];
                // $new->tui('', $registrationId, $data);
               
            }
            //            db('payment')->where(['payment_id' => $order_status['project']])->update($upt);
//            $res = db('recharge')->where('recharge_id', $order_status['recharge_id'])->update($updata);
            if ($res) {
                $start     = strtotime(date('Y-m-01 00:00:00', time()));//获取指定月份的第一天
                $end       = strtotime(date('Y-m-t 23:59:59', time())); //获取指定月份的最后一天
                $customers = db('order')
                    ->field('order.assignor,order.order_id,order.state,order.order_no,us.mobile,order.created_time,order.channel_details,order.notcost_time,order.channel_id,chanel.thousand,chanel.thousand,chanel.Included,channel_details.Included as Includeds,channel_details.thousand as thousands,channel_details.title as titles,order.tui_jian,order.tui_role,order.pro_id')
                    ->join('user us', 'us.user_id=order.assignor', 'left')
                    ->join('chanel', 'order.channel_id=chanel.id', 'left')
                    ->join('channel_details', 'order.channel_details=channel_details.id', 'left')
                    ->where('order.order_no', $order_status['order_no'])
                    ->find();
                $list      = $orderModel->offer($customers['order_id'], 2);
                if ($start <= $customers['created_time'] && $customers['created_time'] <= $end) {
                    if (!empty($customers['channel_details'])) {
                        if ($list['amount'] < $customers['thousands'] && $customers['Includeds'] == 1 && $customers['channel_details'] != 96) {
                            $time = time();
                        } else {
                            if ($customers['channel_details'] == 96 && $list['amount'] >= 1000 && $customers['thousands'] == 1) {
                                $time = '';
                            } else {
                                $time = $customers['notcost_time'];
                            }
                            
                        }
                    } else {
                        if ($list['amount'] < $customers['thousand'] && $customers['Included'] == 1 && $customers['channel_id'] != 96) {
                            $time = time();
                        } else {
                            $time = $customers['notcost_time'];
                        }
                    }
                } else {
                    $time = $customers['notcost_time'];
                }
                $offer             = $orderModel->TotalProfit($customers['order_id']);
                $all_amount_main   = strval($offer['MainMaterialMoney']);
                $all_amount_agency = strval($offer['agencyMoney']);
                if ($customers['state'] == 3) {
                    $paymentMoney = db('payment')->where('payment.orders_id', $customers['order_id'])->whereRaw('money>0 and IF(weixin=2,success=2,success=1) and orders_id>0')->sum('money');
                    
                    if ($paymentMoney / bcadd($all_amount_main, $all_amount_agency, 2) >= 0.499 || (config('cityId')=='246' && $paymentMoney / bcadd($all_amount_main, $all_amount_agency, 2) >= 0.35)) {
                      
                        if (bcadd($all_amount_main, $all_amount_agency, 2) >= 10000 || ($all_amount_main < 10000 && $order_payment_nodes != 0) || $all_amount_main == '0.00' || $paymentMoney >= bcadd($all_amount_main, $all_amount_agency, 2)) {
                            $common->CommissionCalculation($customers['order_id'], $orderModel);
                            db('order')->where(['order_id' => $customers['order_id']])->update(['state' => 4, 'notcost_time' => $time]);
                            remind($customers['order_id'], 4);
                        }
                    }
                    $envelope = db('envelopes_product')->join('envelopes', 'envelopes.envelopes_id=envelopes_product.envelopes_id', 'left')->where('envelopes.ordesr_id', $customers['order_id'])->where('envelopes.type', 1)->where('envelopes_product.state', 1)->field('products_id,products_type')->select();
                    foreach ($envelope as $l) {
                        if ($l['products_type'] == 1) {
                            db('products', config('database.zong'))->where('id', $l['products_id'])->setInc('count_1', 1);
                        } else {
                            db('products_v2', config('database.zong'))->where('id', $l['products_id'])->setInc('count_1', 1);
                        }
                        
                    }
                    
                    $Client = new \app\api\model\KafkaProducer();
                    $Client->add($customers['order_id'], 'u8c_bdjobbasfil_save');
                    sendOrder($customers['order_id']);
                }
                
                $contractpath = ROOT_PATH . 'public/qrcode/' . $attr['outtrxid'] . '.png';
                if (file_exists($contractpath)) {
                    unlink($contractpath);
                }
                
            }
            
        }
    }
    
    
    /*
      * 通联支付开发者中心回调
      */
    
    public function allpay(OrderModel $orderModel, \app\api\model\Common $common)
    {
        $receipt = file_get_contents("php://input");
        if ($receipt == null) {
            $receipt = $GLOBALS['HTTP_RAW_POST_DATA'];
        }
        
        db()->startTrans();
        parse_str($receipt, $query_arr);
        $receipt = $query_arr;
        $attr    = $receipt;
        try {
            $order_status = db('recharge')
                ->join('order', 'order.order_no=recharge.order_no', 'left')
                ->join('user us', 'order.assignor=us.user_id', 'left')
                ->join('chanel', 'order.channel_id=chanel.id', 'left')
                ->join('channel_details', 'order.channel_details=channel_details.id', 'left')
                ->where('recharge.order_nos', $receipt['cusorderid'])
                ->field('us.store_id,recharge.*,order.assignor,order.order_id,order.order_no,order.state,order.order_no,us.mobile,order.created_time,order.channel_details,order.notcost_time,order.channel_id,chanel.thousand,chanel.title,channel_details.Included as Includeds,channel_details.thousand as thousands,channel_details.title as titles,order.tui_jian,order.tui_role,order.pro_id,order.company_id')
                ->find();
            $encryption   = $common->encryption($order_status['company_id']);
//            if(empty($encryption[1])){
//                throw new Exception('加密签名获取失败');
//            }
            $receipt['key'] = $encryption[1];
//            $receipt['key'] = '55265108912';
            unset($receipt['sign']);
            $sign = AppUtil::Sign($receipt);
            
            if ($sign == strtolower($attr['sign'])) {
                if ($order_status['status'] == 1) {
                    $this->return_success();
                } else {
                    $updata['status']          = 1;
                    $updata['last_login_time'] = time();
                    $upt['success']            = 2;
                    $upt['uptime']             = time();
                    db('payment')->where(['payment_id' => $order_status['project']])->update($upt);
                    db('recharge')->where('recharge_id', $order_status['recharge_id'])->update($updata);
                    \db('order_times')->where('order_id', $order_status['order_id'])->where('first_payment_time', 0)->update(['first_payment_time' => $updata['last_login_time']]);
                    if (isset($order_status['youhui_id']) && $order_status['youhui_id'] != '') {
                        if ($order_status['coupon_version'] == 1) {
                            db('coupon_user', config('database.zong'))->where(['id' => $order_status['youhui_id']])->update(['usage_status' => 2, 'usage_time' => time()]);
                        } else {
                            
                            db('discount')->where(['youhui_id' => $order_status['youhui_id'], 'customers_id' => $order_status['customers_id']])->update(['status' => 1]);
                        }
                    }
                    
                    $start = strtotime(date('Y-m-01 00:00:00', time()));//获取指定月份的第一天
                    $end   = strtotime(date('Y-m-t 23:59:59', time())); //获取指定月份的最后一天
                    $cust  = db('customers')->where('customers_id', $order_status['customers_id'])->find();
                    $list  = $orderModel->offer($order_status['order_id'], 2);
                    if ($start <= $order_status['created_time'] && $order_status['created_time'] <= $end) {
                        if (!empty($order_status['channel_details'])) {
                            if ($list['amount'] < 1000 && $order_status['thousands'] == 1 && $order_status['channel_details'] != 96) {
                                $time = time();
                            } else {
                                if ($order_status['channel_details'] == 96 && $list['amount'] >= 1000 && $order_status['thousands'] == 1) {
                                    $time = '';
                                } else {
                                    $time = $order_status['notcost_time'];
                                }
                                
                            }
                        } else {
                            if ($list['amount'] < 1000 && $order_status['thousand'] == 1 && $order_status['channel_id'] != 96) {
                                $time = time();
                            } else {
                                $time = $order_status['notcost_time'];
                            }
                        }
                    } else {
                        $time = $order_status['notcost_time'];
                    }
                    $orderState = 0;
                    if ($order_status['state'] == 3) {
                        db('order')->where(['order_id' => $order_status['order_id']])->update(['state' => 4, 'notcost_time' => $time]);
                        $orderState = 4;
                        remind($order_status['order_id'], 4);
                    }
                    
                    sendMsg($order_status['mobile'], 9580, [empty($cust['username']) ? '先生' : $cust['username'], $order_status['order_no'], $order_status['money']]);
                    db()->commit();
                    $this->return_success();
                    if ($orderState == 4) {
                        $common->CommissionCalculation($order_status['order_id'], $orderModel, 2);
                    }
                    json_decode(sendOrder($order_status['order_id']), true);
                }
                
                
            } else {
                throw new Exception('签名验证错误');
            }
        } catch (Exception $e) {
            db()->rollback();
            Db::connect(config('database.zong'))->table('tonglian_payment')->insert([
                'ls_order' => $receipt['cusorderid'],
                'time' => time(),
                'data' => $receipt,
                'problem' => $e->getMessage(),
            ]);
        }
    }
    
    public function orderAudio(TelephoneNotification $telephoneNotification, OrderModel $orderModel)
    {
        $receipt = file_get_contents("php://input");
        if (!empty($receipt)) {
            journal(['url' => '录音电话记录', 'data' => $receipt], 3);
            // $Jpush   = new Jpush();
            $receipt = json_decode($receipt, true);
            $ccPush  = new ccPush(600, 'template_audio', 'delay_topic', 'template.Audio');
            foreach ($receipt as $item) {
                if (isset($item['out_id']) && $item['out_id'] != '') {
                    $order_audio = \db('order_audio', config('database.zong'))->join('order', 'order.order_id=order_audio.order_id', 'left')->join('user', 'user.user_id=order.assignor', 'left')->where(['order_audio.only_id' => $item['out_id']])->field('order_audio.*,order.assignor,user.registrationId')->find();
                } else {
                    $order_audio = \db('order_audio', config('database.zong'))->join('order', 'order.order_id=order_audio.order_id', 'left')->join('user', 'user.user_id=order.assignor', 'left')->where(['order_audio.telX' => $item['secret_no'], 'customers_mobile' => $item['peer_no']])->field('order_audio.*,order.assignor,user.registrationId')->order('order_audio.id desc')->find();
                }
                
                if ($item['call_type'] == 1 && $item['peer_no'] == $order_audio['customers_mobile']) {
                    $remind = "已接;";
                    if (strtotime($item['release_time']) - strtotime($item['start_time']) == 0) {
                        $remind = "未接;";
                    }
//                    $Jpush->tui("通话提醒", $order_audio['registrationId'], ['type' => 42, 'content' => $remind . date('Y-m-d H:i', time()), 'order_id' => $order_audio['order_id'], 'time' => time(), 'user_id' => $order_audio['assignor']]);
                }
                $order_audio_list   = \db('order_audio_list', config('database.zong'))->where('requestId', $item['call_id'])->where('order_audio_id', $order_audio['id'])->find();
                $order_audio_listId = $order_audio_list['id'];
                if (empty($order_audio_list)) {
                    $order_audio_list   = \db('order_audio_list', config('database.zong'))->insertGetId(['requestId' => $item['call_id'], 'url' => isset($item['record_url']) ? $item['record_url'] : '', 'call_time' => strtotime($item['call_time']), 'startTime' => strtotime($item['start_time']), 'finishTime' => strtotime($item['release_time']), 'order_audio_id' => $order_audio['id'], 'call_type' => $item['call_type'], 'unconnected_cause' => $item['unconnected_cause'], 'user_mobile' => $item['phone_no'], 'telX' => $item['secret_no'], 'customers_mobile' => $item['peer_no']]);
                    $order_audio_listId = $order_audio_list;
                }
                
                if (isset($item['record_url'])) {
                    $ccPush->push($order_audio_listId, 'template_audio', 'delay_topic', 'template.Audio');
                }
                $content = $orderModel->UrbanAccess(substr($order_audio['order_id'], 0, 3));
                if ($content != 0) {
                    $order = Db::connect($content)->table('order_times');
                    
                    $order_times = $order->where('order_id', $order_audio['order_id'])->where('sending_sms', 0)->count();
                    if ($order_times == 1) {
                        $post_data = [
                            'path' => 'pages/shopowner/shopowner',
                            'query' => "id={$order_audio['assignor']}",
                            'env_version' => 'release',
                            'expire_type' => 1,
                            'expire_interval' => 179
                        ];
                        $WxService = new WxService();
                        $url       = $WxService->getWxUrlLink($post_data);
                        publicSendMsg($order_audio['customers_mobile'], 21064, [$url]);
                        Db::connect($content)->table('order_times')->where('order_id', $order_audio['order_id'])->update(['sending_sms' => time()]);
                    }
                }
                
            }
        }
        
        echo json_encode(['code' => 0, 'msg' => ' "成功"']);;
        exit;
    }
    
    public function AudioSecretAsrReport()
    {
        $receipt = file_get_contents("php://input");
        if (!empty($receipt)) {
            journal(['url' => '录音文件', 'data' => $receipt], 3);
            $receipt = json_decode($receipt, true);
            foreach ($receipt as $item) {
                if (isset($item['callId']) && $item['callId'] != '') {
                    \db('order_audio_list', config('database.zong'))->where('requestId', $item['callId'])->update(['content' => !empty($item['sentences']) ? json_encode($item['sentences']) : '']);
                }
                
            }
        }
        echo json_encode(['code' => 0, 'msg' => ' "成功"']);;
        exit;
        
    }
    
    public function AudioSecretRecording()
    {
        $receipt = file_get_contents("php://input");
        if (!empty($receipt)) {
            journal(['url' => '录音音频', 'data' => $receipt], 3);
            $receipt = json_decode($receipt, true);
            foreach ($receipt as $item) {
                $order_audio_list = db('order_audio_list', config('database.zong'))->where('requestId', $item['call_id'])->find();
                if (!empty($order_audio_list) && empty($order_audio_list['oss_url'])) {
                    $url  = $order_audio_list['url'];
                    $path = ROOT_PATHS . '/uploads/';
                    $ch   = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
                    $file = curl_exec($ch);
                    curl_close($ch);
                    $filename = pathinfo($url, PATHINFO_BASENAME);
                    $resource = fopen($path . $filename, 'a');
                    fwrite($resource, $file);
                    fclose($resource);
                    $path       = $path . $filename;
                    $ali        = new Aliyunoss();
                    $oss_result = $ali->upload('audio/' . date('Ymd') . '/' . $order_audio_list['id'] . '.mp3', $path);
                    if ($oss_result['info']['http_code'] == 200) {
                        $paths = parse_url($oss_result['info']['url'])['path'];
                        if (file_exists($path)) {
                            unlink($path);
                        };
                        $telephoneNotification = new TelephoneNotification();
                        $GetSecretAsr          = $telephoneNotification->GetSecretAsrDetailRequest(['callId' => $order_audio_list['requestId'], 'callTime' => date('Y-m-d H:i:s', $order_audio_list['call_time'])]);
                        $oss_url               = 'https://images.yiniao.co' . $paths;
                        $order_audio_list      = \db('order_audio_list', config('database.zong'))->where('id', $order_audio_list['id'])->update(['oss_url' => $oss_url, 'content' => !empty($GetSecretAsr) ? json_encode($GetSecretAsr) : '']);
                        Log::write(json_encode(['APP' => '店长端电话处理', 'log' => "成功" . $order_audio_list['id']]), true);
                    }
                    Log::write(json_encode(['APP' => '店长端电话处理', 'log' => "失败" . $order_audio_list['id']], true));
                }
                
            }
        }
        echo json_encode(['code' => 0, 'msg' => ' "成功"']);;
        exit;
        
    }

    /**
     * 微信上门打卡
     * @param \app\api\model\OrderModel $orderModel
     * @param \app\api\model\Common $common
     * @return void
     */
    public function GenerateRewards(OrderModel $orderModel, \app\api\model\Common $common)
    {
        $param = \request()->get();
        if (!isset($param['orderId']) || empty($param['orderId'])) {
            jso_data([], 300, "参数不存在");
        }
        $clock_in = \db('clock_in')->where('order_id', $param['orderId'])->select();
        db('log', config('database.zong'))->insert(['ord_id' =>  $param['orderId'], 'type' => 91, 'content' => json_encode($clock_in), 'created_at' => time()]);
        if (count($clock_in) == 1) {
            $common->CommissionCalculation($param['orderId'], $orderModel, 1,3);
           
        }
        jso_data(md5($param['orderId']), 200, "");
    }
    
    public function whentheCallIsInitiated(Common $common)
    {
        $receipt = file_get_contents("php://input");
        if (!empty($receipt)) {
            journal(['url' => '呼叫发起时话单报告', 'data' => $receipt], 3);
            $Jpush   = new Jpush();
            $receipt = json_decode($receipt, true);

            foreach ($receipt as $item) {
                $order_audio = \db('order_audio', config('database.zong'))->join('order', 'order.order_id=order_audio.order_id', 'left')->join('user', 'user.user_id=order.assignor', 'left')->where('order.telephone', $item['peer_no'])->field('order.assignor,order.contacts,order.order_id,order.telephone,order.addres,user.registrationId,order_audio.call_type')->order('order.order_id desc')->find();
                if ($order_audio['call_type'] == 0 && !empty($order_audio['registrationId'])) {
                    $content = $common->city($order_audio['order_id'])['db'];
                    if ($content != 0) {
                        $Jpush->tui("通话提醒", $order_audio['registrationId'], ['type' => 42, 'content' => "客户:" . $order_audio['contacts'] . ";联系地址:" . $order_audio['addres'] . "时间" . date('Y-m-d H:i', time()), 'order_id' => $order_audio['order_id'], 'time' => time(), 'user_id' => $order_audio['assignor']], $content);
                    }
                }
            }
        }
        echo json_encode(['code' => 0, 'msg' => ' "成功"']);;
        exit;
    }
    
    /**
     * Summary of pushReimbursement  手动推送报销审核
     * @param \app\api\model\Approval $approval
     * @return never
     */
    public function pushReimbursement(Approval $approval)
    {
        
        $reimbursement = db('reimbursement', config('database.zong'))->field('reimbursement.*,order_info.assignor')->join('order', 'order.order_id=reimbursement.order_id', 'left')->join('order_info', 'order_info.order_id=reimbursement.order_id', 'left')->whereNull('order.cleared_time')->where(function ($quer) {
            $quer->where('reimbursement.status', 0)->whereOr('reimbursement.status', 3);
        })->select();
        foreach ($reimbursement as $item) {
            $approval_info = \db('approval_info', config('database.zong'))->where('relation_id', $item['id'])->find();
            if (empty($approval_info) && (($item['type'] == 2 && $item['status'] == 3) || ($item['type'] == 1 && $item['status'] == 0))) {
                $data[] = $item;
                $title  = array_search($item['classification'], array_column($approval->listReimbursement(), 'type'));
                $title  = $item['assignor'] . $approval->listReimbursement()[$title]['name'] . '报销';
                $approval->Reimbursement($item['id'], $title, $item['assignor'], $item['classification'], 5);
            }
            
        }
        dump($data);
        die;
        
    }
    public function allCompleted($orderId = 0)
    {
        $order = db('order', config('database.zong'))
            ->join('order_aggregate', 'order.order_id=order_aggregate.order_id', 'left');
        if ($orderId != 0) {
            $order->where('order.order_id', $orderId);
        }
        $order = $order->join('startup', 'order.order_id=startup.orders_id', 'left')->join('user', 'order.assignor=user.user_id', 'left')->field('order.finish_time,order.agency_finish_time,order_aggregate.main_price,order_aggregate.agent_price,startup.up_time,order.order_id,order.cleared_time,order.settlement_time,user.completion_acceptance')->where('order.state', 7)->select();
        foreach ($order as  $l) {
            $deadline_time = 0;
            if ($l['completion_acceptance'] == 1) {
                if ($l['main_price'] == 0 && $l['agent_price'] != 0 && !empty($l['agency_finish_time']) && empty($l['settlement_time'])) {
                    $deadline_time = $l['agency_finish_time'];
                }
                if ($l['main_price'] != 0 && $l['agent_price'] == 0 && !empty($l['finish_time']) && empty($l['cleared_time'])) {
                    $deadline_time = $l['finish_time'];
                }
                if ($l['main_price'] != 0 && $l['agent_price']  != 0 && !empty($l['finish_time']) && !empty($l['agency_finish_time']) && empty($l['settlement_time']) && empty($l['cleared_time'])) {
                    $deadline_time = max([$l['finish_time'], $l['agency_finish_time']]);
                }
                if ($deadline_time > 0) {
                    Db::connect(config('database.zong'))->table('order_delay_deduction')->where(['order_id' => $l['order_id']])->update(['delete_time' => time()]);
                    $work_check_id    = db('work_check', config('database.zong'))->where(['work_check.type' => 1, 'order_id' => $l['order_id'], 'work_check.work_title_id' => 5])->where('delete_time', 0)->find();
                    $order_completion = Db::connect(config('database.zong'))->table('order_completion')->where(['work_check_id' => $work_check_id['id'], 'order_id' => $l['order_id']])->whereIn('inspection_type', '0,1,3')->order('id desc')->find();
                    if (empty($order_completion)) {
                        Db::connect(config('database.zong'))->table('order_completion')->insert(['work_check_id' => $work_check_id['id'], 'order_id' => $l['order_id'], 'deadline_time' =>  strtotime(date('Y-m-d 23:59:59', $deadline_time + 3 * 86400)), 'create_time' => $deadline_time, 'share' => 1]);
                    } else {
                        Db::connect(config('database.zong'))->table('order_completion')->where('id', $order_completion['id'])->update(['share' => 1]);
                    }
                    // $day = floor($deadline_time - $l['up_time']) / (3600 * 24);
                    // if ($day > 0) {
                    //                        Db::connect(config('database.zong'))->table('order_delay_deduction')->insert(['finished_time'=> $deadline_time,'order_id'=>$l,'create_time'=>time(),'state'=>0,'day'=>$day]);
                    // }
                }
            }
        }
    }
        
    public function mainMaterialAddition()
    {
        $param = \request()->get();
        
        db('order_setting')->where('order_id', $param['orderId'])->update(['stop_agent_reimbursement' => 1]);
        $agencyTask = new \app\api\model\AgencyTask();
        $agencyTask->addAllInit($param['orderId']);
        jso_data(null, 200);
        
    }
    /**
     * Summary of 手动转入施工中
     * @param \app\api\model\OrderModel $orderModel
     * @param \app\api\model\Common $common
     * @return void
     */
    public function manuallyTransitioningIntoConstruction(OrderModel $orderModel, \app\api\model\Common $common){
        $param = \request()->get();
        $order_id=db('order')->where(['order_no' => $param['order_no']])->value('order_id');
        $customers['order_id']=$order_id;
        $common->CommissionCalculation($customers['order_id'], $orderModel);
        db('order')->where(['order_id' => $customers['order_id']])->update(['state' => 4]);
         remind($customers['order_id'], 4);
    }
}
